/**
 * 
 */
package com.m7012e.a_remote.android_remote.network.protocol;

import java.io.IOException;
import java.util.SortedMap;
import java.util.Timer;
import java.util.TimerTask;

import com.leoj.utils.Handler;
import com.leoj.utils.tcp_network.tcp_server.SingleThreadTcpServer;
import com.m7012e.a_remote.android_remote.network.protocol.echoProtocol.DaemonListingProtocolFactory;
import com.m7012e.a_remote.commons.ARemoteMulticastSender;
import com.m7012e.a_remote.communication.Daemon;
import com.m7012e.a_remote.communication.DisplayDiscoveryMessage;
import com.m7012e.a_remote.communication.positioning.WifiRoughlyPosition;

/**
 * @author leoj
 *
 */
public class ARemoteNetworking {
	
	/**
	 * 
	 */
	public ARemoteNetworking() {
		// TODO Auto-generated constructor stub
	}
	
	public static void startDiscovery(final Handler<SortedMap<Daemon,Integer>> discoveryOverhandler, final WifiRoughlyPosition currentPosition) throws IOException{
		final DaemonListingProtocolFactory factory = new DaemonListingProtocolFactory();
		final SingleThreadTcpServer tcpServer = new SingleThreadTcpServer(8707, factory);
		final TimerTask stopDiscovery = new TimerTask() {
			@Override
			public void run() {
				tcpServer.stopAsap();
				discoveryOverhandler.handle(factory.getCurrentAvailable());
			}
		};
		Thread thread = new Thread(){
			@Override
			public void run() {
				try {
					DisplayDiscoveryMessage msg = new DisplayDiscoveryMessage(tcpServer.getServerStrAddress(), tcpServer.getServerPort(), currentPosition);
					ARemoteMulticastSender.INSTANCE.sendMessage(msg);
					
					Timer timer = new Timer();
					timer.schedule(stopDiscovery, 3000);
					//aka let's stop when we waited for too long 
					Timer justChecking = new Timer();
					justChecking.scheduleAtFixedRate(new TimerTask() {
						@Override
						public void run() {
							if(factory.getAvailableAnswers()>3 || factory.getTotalAnswers() > 8){
								stopDiscovery.run();
							}
						}
					}, 100, 100);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		};
		factory.startListing();
		tcpServer.start();
		thread.start();
	}
	
	public static void requestDisplay(Daemon d){
		
	}
}
